<?php

namespace App\Notifications\Train\TrainOrder;

use App\Facades\Sms;
use App\Models\Train\TrainOrders\TrainOrder;
use App\Models\Train\TrainOrderTrain\TrainOrderTrain;
use App\Models\User\Repositories\Interfaces\UserRepositoryInterface;
use App\Models\User\User;
use App\Trip\Notify\Channel\SmsChannel;
use App\Trip\Notify\Channel\WechatMiniAppChannel;
use App\Trip\Notify\Channel\WechatOfficialChannel;
use App\Trip\Notify\Sms\Messages\Train\SnapExpiredNotifyMessage;
use App\Trip\Wechat\Account\WechatMiniAppLogin;
use Carbon\Carbon;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class SnapExpiredNotify extends Notification
{
    use Queueable;


    private TrainOrder      $order;
    private ?User           $user;
    private TrainOrderTrain $train;

    /**
     * Create a new notification instance.
     *
     * @return void
     */

    public function __construct(TrainOrder $order)
    {
        $this->order = $order;
        $userRepo    = app(UserRepositoryInterface::class);
        $this->user  = $userRepo->getUserByUserId($this->order->getUserId());
        $this->train = $this->order->getMainTrain();

    }

    /**
     * Get the notification's delivery channels.
     *
     * @param mixed $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [SmsChannel::class, WechatMiniAppChannel::class, WechatOfficialChannel::class,];
    }

    /**
     * 获取短信通知。
     *
     * @param mixed $notifiable
     *
     * @throws Exception
     */
    public function toSms($notifiable)
    {
        try {
            $message = new SnapExpiredNotifyMessage($this->order);
            Sms::send($this->order->getMobile(), $message);
        } catch (Exception $e) {
            Log::error("抢票过期,短信发送失败:{$e->getMessage()},{$this->order->getOrderSn()}");
        }
    }


    /**
     * 获取微信小程序通知。
     *
     * @param mixed $notifiable
     *
     */
    public function toWechatMiniApp($notifiable)
    {
        $user = $this->user?->getMiniAppUser();
        if (!$user) {
            Log::info("抢票过期,我发微信小程序订阅消息未找到用户,{$this->order->getOrderSn()}");
        }
        $config = config('weixin.miniapp')['message']['subscribes'] ?? [];
        if (empty($config)) {
            Log::info("抢票过期,我发微信小程序订阅消息未找到配置文件,{$this->order->getOrderSn()}");
            return;
        }

        $collect     = collect($config)->where('type', 'train_order_snap_expired');
        $template_id = $collect->value('template_id');
        $msg         = [
            "touser"            => $user->getOpenId(),
            "template_id"       => $template_id,
            "page"              => "pages/order/order",
            "miniprogram_state" => "developer",
            "lang"              => "zh_CN",
            "data"              => [
                'short_thing1'      => [
                    'value' => __('抢票过期'),//抢票结果
                ],
                'character_string2' => [
                    'value' => $this->order->getTrainCode(),
                ],
                'thing3'            => [
                    'value' => Str::limit("{$this->train->getFromName()} -> {$this->train->getToName()}", 80, ""),
                ],
                'time4'             => [
                    'value' => Carbon::parse($this->order->getTrainDate())->format("Y年m月d日 H:i;s"),
                ],
            ],
        ];

        if (empty($msg)) {
            return;
        }


        $w       = new WechatMiniAppLogin();
        $app     = $w->application();
        $client  = $app->getClient();
        $content = $client->postJson('/cgi-bin/message/subscribe/send', $msg);
        Log::info("抢票过期,微信小程序订阅消息:".$content->getContent()."-{$this->order->getOrderSn()}");

    }

    /**
     * 获取微信公众号通知。
     *
     * @param mixed $notifiable
     *
     */
    public function toWechatOfficial($notifiable)
    {

    }

}
